package com.my.study.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 服务端
 *
 * @author: yidujun
 * @create: 2021/04/07 16:18
 */
public class GroupChatServer {

    private Selector selector;
    private ServerSocketChannel listenChannel;

    private static final int PORT = 6667;

    public GroupChatServer() {
        try {
            // 得到选择器
            selector = Selector.open();
            // ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            // 绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置非阻塞模式
            listenChannel.configureBlocking(false);
            // 将该listenChannel注册到选择器selector中
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        try {
            // 循环处理
            while (true) {
                // 查找有事件的通道个数
                int count = selector.select();
                // 有事件要处理
                if (count > 0) {
                    // 遍历得到selectedKey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        // 取出selectionKey
                        SelectionKey selectionKey = iterator.next();
                        // 监听到accept
                        if (selectionKey.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress() + "上线");
                        }
                        // 通道发送read事件，即通道是可读的状态
                        if (selectionKey.isReadable()) {
                            // 处理读
                            readData(selectionKey);
                        }
                        // 移除当前key，防止重复消费
                        iterator.remove();
                    }

                } else {
                    System.out.println("等待...");
                }
            }
        } catch (Exception e) {

        } finally {

        }
    }

    /**
     * 读取客户端消息
     * @param key
     */
    public void readData(SelectionKey key) {
        SocketChannel sc = null;
        try {
            // 得到Channel
            sc = ((SocketChannel) key.channel());
            // 创建buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int count = sc.read(byteBuffer);
            if (count > 0) {
                String msg = new String(byteBuffer.array());
                System.out.println("form客户端: " + msg);
                // 向其它的客户端转发消息(去掉自己),专门写一个方法来处理
                sendInfoToOtherClients(msg, sc);
            }

        } catch (IOException e) {

        }
    }

    /**
     * 转发消息给其它客户(通道)
     *
     * @param msg 消息
     * @param self
     */
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中...");
        for (SelectionKey key : selector.selectedKeys()) {
            // 通过 key 取出对应的 SocketChannel
            Channel targetChannel = key.channel();
            // 排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                // 转型
                SocketChannel dest = (SocketChannel) targetChannel;
                // 将 msg 存储到 buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                // 写入通道
                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
